package com.gzh.system.service.impl;

import com.gzh.core.chche.service.CacheManage;
import com.gzh.core.dao.mapper.AcademyMapper;
import com.gzh.core.dao.mapper.ChooseMapper;
import com.gzh.core.dao.mapper.ClassMapper;
import com.gzh.core.dao.mapper.UserMapper;
import com.gzh.core.dao.po.AcademyEntity;
import com.gzh.core.dao.po.ChooseEntity;
import com.gzh.core.dao.po.ClassEntity;
import com.gzh.core.dao.po.UserEntity;
import com.gzh.core.util.NumericHelper;
import com.gzh.core.util.constant.ErrorCode;
import com.gzh.core.util.exception.BusinessException;
import com.gzh.system.service.MailService;
import com.gzh.system.service.SystemService;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.xssf.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;
import tk.mybatis.mapper.entity.Condition;

import java.io.*;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author guanzh
 * @Date 2021/12/27 11:30
 * @Description
 */
@Service
@Slf4j
public class SystemServiceImpl implements SystemService {

    @Autowired
    private AcademyMapper academyMapper;
    @Autowired
    private ClassMapper classMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ChooseMapper chooseMapper;
    @Autowired
    private MailService mailService;

    @Override
    public void readExcel(MultipartFile file, Integer userId) {
        String originalFilename = file.getOriginalFilename();
        if (!originalFilename.endsWith(".xlsx")){
            throw new BusinessException(ErrorCode.ADD_131);
        }
        UserEntity userEntityQuery = new UserEntity();
        userEntityQuery.setUserId(userId);
        UserEntity user = userMapper.selectOne(userEntityQuery);
        Integer schoolId = user.getSchoolId();
        List<UserEntity> userEntityList = new ArrayList<>();
        try {
            InputStream in = file.getInputStream();
            XSSFWorkbook sheets = new XSSFWorkbook(in);
            //拿第一个页表
            XSSFSheet sheetAt = sheets.getSheetAt(0);
            //第一行 标题字段
            XSSFRow titleRow = sheetAt.getRow(0);

            //学院和专业和学校
            List<AcademyEntity> academyEntities = academyMapper.selectAll();
            Map<String, Integer> academyMap = academyEntities
                    .stream()
                    .collect(Collectors.toMap(AcademyEntity::getAcademyName, AcademyEntity::getAcademyId));

            List<ClassEntity> classEntities = classMapper.selectAll();
            Map<String, Integer> classMap = classEntities
                    .stream()
                    .collect(Collectors.toMap(ClassEntity::getClassName, ClassEntity::getClassId));

            for (int i = 1; i < sheetAt.getPhysicalNumberOfRows(); i++) {
                //第i行
                XSSFRow row = sheetAt.getRow(i);
                //学生
                UserEntity userEntity = new UserEntity();
                // 读取每一格内容
                for (int index = 0; index < titleRow.getPhysicalNumberOfCells(); index++) {
                    XSSFCell titleCell = titleRow.getCell(index);
                    XSSFCell cell = row.getCell(index);
                    if (cell == null){
                        continue;
                    }
                    cell.setCellType(CellType.STRING);
                    if ( cell.getStringCellValue().equals("")) {
                        continue;
                    }
                    this.buildUser(userEntity,getString(titleCell),getString(cell),academyMap,classMap);
                }
                userEntity.setPassword("99999999");
                userEntity.setRoleId(0);
                userEntity.setSchoolId(schoolId);
                userEntityList.add(userEntity);
            }
        } catch (IOException e) {
            log.error("解析excel添加人员错误");
            throw new BusinessException(ErrorCode.ADD_130);
        }
        //添加表中
        if (!CollectionUtils.isEmpty(userEntityList)){
            List<String> telList = userEntityList.stream().map(t -> t.getTel())
                    .collect(Collectors.toList());
            Condition uCondition = new Condition(UserEntity.class);
            uCondition.createCriteria().andIn("tel",telList);
            List<UserEntity> entityList = userMapper.selectByCondition(uCondition);
            List<String> filterUserList = new ArrayList<>();
            if (!CollectionUtils.isEmpty(entityList)){
                 filterUserList = entityList.stream().map(t -> t.getTel())
                        .collect(Collectors.toList());
            }
            List<String> finalFilterUserList = filterUserList;
            userEntityList = userEntityList.stream().filter(t->!finalFilterUserList.contains(t.getTel()))
                    .collect(Collectors.collectingAndThen(
                            Collectors.toCollection(()->new TreeSet<>(Comparator.comparing(UserEntity::getTel))),ArrayList::new)
                    );
            userMapper.insertList(userEntityList);
        }
    }

    @Override
    public void sendMailToCheck(Integer courseId,Integer checkId) {
        Condition chooseCondition = new Condition(ChooseEntity.class);
        chooseCondition.createCriteria().andEqualTo("courseId",courseId);
        List<ChooseEntity> chooseEntityList = chooseMapper.selectByCondition(chooseCondition);
        List<Integer> userIdList = chooseEntityList.stream().map(t -> t.getUserId()).distinct().collect(Collectors.toList());
        Condition userCondition = new Condition(UserEntity.class);
        userCondition.createCriteria().andIn("userId",userIdList);
        List<UserEntity> userEntityList = userMapper.selectByCondition(userCondition);
        mailService.checkMail(userEntityList,checkId);
    }

    /**
     * 把单元格的内容转为字符串
     *
     * @param xssfCell 单元格
     * @return String
     */
    public static String getString(XSSFCell xssfCell) {
        if (xssfCell == null) {
            return "";
        }
        if (xssfCell.getCellTypeEnum() == CellType.NUMERIC) {
            return String.valueOf(xssfCell.getNumericCellValue());
        } else if (xssfCell.getCellTypeEnum() == CellType.BOOLEAN) {
            return String.valueOf(xssfCell.getBooleanCellValue());
        } else {
            return xssfCell.getStringCellValue();
        }
    }

    public static UserEntity buildUser(UserEntity userEntity, String titleValue, String cellValue, Map<String, Integer> academyMap, Map<String, Integer> classMap) {
        if (titleValue.equals("学号") || titleValue.equals("sno")){
            userEntity.setStuId(cellValue);
        }
        if (titleValue.equals("姓名") || titleValue.equals("name")){
            userEntity.setFullName(cellValue);
        }
        if (titleValue.equals("性别") || titleValue.equals("sex")){
            userEntity.setSex(cellValue.equals("男")? 1 : 0);
        }
        if (titleValue.equals("年级") || titleValue.equals("grade")){
            userEntity.setGrade(NumericHelper.toInteger(cellValue));
        }
        if (titleValue.equals("电话") || titleValue.equals("tel")){
            userEntity.setTel(cellValue);
        }
        if (titleValue.equals("邮箱") || titleValue.equals("mail")){
            userEntity.setMail(cellValue);
        }
        if (titleValue.equals("学院") || titleValue.equals("academy")){
            userEntity.setAcademyId(academyMap.get(cellValue));
        }
        if (titleValue.equals("班级") || titleValue.equals("class")){
            userEntity.setClassId(classMap.get(cellValue));
        }
        return userEntity;
    }
}
